package logic

import (
	"context"
	"fmt"

	"probe-scheduler/internal/svc"
	pb "probe-scheduler/pb/scheduler"

	"github.com/zeromicro/go-zero/core/logx"
)

type PauseTaskLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPauseTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PauseTaskLogic {
	return &PauseTaskLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PauseTaskLogic) PauseTask(in *pb.PauseTaskRequest) (*pb.PauseTaskResponse, error) {
	if in.TaskId == 0 {
		return &pb.PauseTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: "task id is required",
			},
		}, nil
	}

	// 暂停任务（先修改数据库）
	if err := l.svcCtx.TaskDao.PauseTask(l.ctx, in.TaskId); err != nil {
		return &pb.PauseTaskResponse{
			Base: &pb.CommonResponse{Success: false, Message: fmt.Sprintf("暂停失败: %v", err)},
		}, nil
	}

	// 从调度器中暂停任务
	err := l.svcCtx.Scheduler.PauseTask(in.TaskId)
	if err != nil {
		l.Errorf("failed to pause task %s: %v", in.TaskId, err)
		return &pb.PauseTaskResponse{
			Base: &pb.CommonResponse{
				Success: false,
				Message: fmt.Sprintf("failed to pause task: %v", err),
			},
		}, nil
	}

	return &pb.PauseTaskResponse{
		Base: &pb.CommonResponse{
			Success: true,
			Message: "task paused successfully",
		},
	}, nil
}
